<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.categoryId ? $t('crud.addTitle') : $t('groups.edit')"
    :close-on-click-modal="false"
    width="700px"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="170px"
      @submit.prevent
      @keyup.enter="onSubmit()"
    >
      <!-- 语言选择 -->
      <el-form-item
        v-if="langItemList.length > 1"
        :label="$t('product.chooseLanguage')"
      >
        <el-select
          v-model="curLang"
          multiple
          :placeholder="$t('tip.select')"
          style="width: 100%;"
          @change="selectLang"
        >
          <el-option
            v-for="item in langItemList"
            :key="item.lang"
            :label="item.name"
            :value="item.lang"
          />
        </el-select>
      </el-form-item>
      <!-- 分类名称 -->
      <template v-if="dataForm.type !== 2">
        <div
          v-for="(item,index) in categoryLangList"
          :key="index"
        >
          <el-form-item
            :required="true"
            :label="$t('publics.categoryCn') + (langItemList.length === 1 ? '' : `(${item.langName})`)"
          >
            <el-input
              v-model.trim="item.categoryName"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>
        </div>
      </template>
      <el-form-item
        v-if="dataForm.type !== 2"
        :label="$t('hotSearch.seq')"
        prop="seq"
      >
        <el-input
          v-model.number="dataForm.seq"
          :min="0"
          :max="999999999"
          :label="$t('hotSearch.seq')"
          type="number"
          @blur="handleSortValue"
        />
      </el-form-item>
      <el-form-item
        :label="$t('product.status')"
        prop="status"
      >
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="0">
            {{ $t("live.offline") }}
          </el-radio>
          <el-radio :label="1">
            {{ $t("publics.normal") }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t("crud.filter.cancelBtn") }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="onSubmit"
        >
          {{ $t("crud.filter.submitBtn") }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { ElMessage } from 'element-plus'
import { treeDataTranslate, idList } from '@/utils'

const emit = defineEmits(['refreshDataList'])

const dataFormRef = ref(null)
const dataForm = reactive({
  categoryId: 0,
  grade: 0,
  categoryName: '',
  categoryNameEn: '',
  seq: 1,
  status: 1,
  parentId: 0,
  pic: ''
})

// eslint-disable-next-line no-unused-vars
const validateSeq = (rule, value, callback) => {
  const reg = /[^-\d]/
  const regs = /^\s+$/g
  if (value == null || value === '') {
    dataFormRef.value.clearValidate('seq')
    callback()
  } else if (reg.test(value)) {
    callback(new Error($t('prodTag.tips')))
  } else if (regs.test(value)) {
    callback(new Error($t('publics.categoryNoNull')))
  } else {
    callback()
  }
}
const dataRule = reactive({
  pic: [
    { required: true, message: $t('publics.imageNoNull'), trigger: 'blur' }
  ],
  seq: [
    { validator: validateSeq }
  ]
})

const categoryLangList = ref([])
const visible = ref(false)
let categoryList = []
let selectedCategory = []
const init = (id) => {
  dataForm.categoryId = id || 0
  http({
    url: http.adornUrl('/prod/category/listCategory'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    categoryList = treeDataTranslate(data, 'categoryId', 'parentId')
  }).then(() => {
    visible.value = true
    nextTick(() => {
      dataFormRef.value?.resetFields()
      selectedCategory = []
    })
  }).then(() => {
    if (dataForm.categoryId) {
      // 修改
      http({
        url: http.adornUrl(`/prod/category/info/${dataForm.categoryId}`),
        method: 'get',
        params: http.adornParams()
      }).then(({ data }) => {
        dataForm.categoryId = data.categoryId
        dataForm.categoryName = data.categoryName
        dataForm.categoryNameEn = data.categoryNameEn
        dataForm.seq = data.seq
        dataForm.pic = data.pic
        dataForm.parentId = data.parentId
        dataForm.status = data.status
        selectedCategory = idList(categoryList, data.parentId, 'categoryId', 'children').reverse()
        categoryLangList.value = data.categoryLangList
        getLangList()
      })
    } else {
      getLangList()
      categoryLangList.value = []
    }
  })
}

const langItemList = ref([]) // 语言列表
const curLang = ref([]) // 当前所选语言
const masterLangInfo = { name: '', lang: '' }
const getLangList = () => {
  http({
    url: http.adornUrl('/sys/lang'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    if (data) {
      const info = data
      masterLangInfo.name = info.name
      masterLangInfo.lang = info.lang
      langItemList.value = info.langItemList
      if (dataForm.categoryId) {
        const curLang = []
        const temPcateLangList = []
        for (const item of langItemList.value) {
          const fd = categoryLangList.value.find(it => it.lang === item.lang)
          if (fd) {
            fd.langName = item.name
            temPcateLangList.push(fd)
            curLang.push(item.lang)
          }
        }
        categoryLangList.value = temPcateLangList
        selectLang(curLang)
      } else {
        // 设置默认主语言
        selectLang([info.lang])
      }
    }
  })
}
// 多选框默认选择主语言
const selectLang = (value) => {
  curLang.value = value
  // 设置主语言不可删除
  if (!curLang.value.includes(masterLangInfo.lang)) {
    curLang.value.unshift(masterLangInfo.lang)
  }
  // 分类名称
  const tempArr = categoryLangList.value.filter(item => curLang.value.includes(item.lang))
  curLang.value.forEach((item, index) => {
    if (!tempArr.find(f => f.lang == item)) {
      const fd = langItemList.value.find(it => it.lang === item)
      if (fd) {
        tempArr.splice(index, 0, { langName: fd.name, lang: item, categoryId: dataForm.categoryId, categoryName: '' })
      }
    }
  })
  categoryLangList.value = tempArr
}
// 表单提交
const onSubmit = () => {
  if (selectedCategory.length === 1) {
    dataForm.grade = 0
  }
  if (selectedCategory.length === 2) {
    dataForm.grade = 1
  }
  if (selectedCategory.length === 3) {
    dataForm.grade = 2
  }
  for (const item of categoryLangList.value) {
    if (!item.categoryName) {
      ElMessage.error($t('category.categoryNameNull'))
      return
    }
  }
  dataFormRef.value?.validate((valid) => {
    if (valid) {
      http({
        url: http.adornUrl('/prod/category'),
        method: dataForm.categoryId ? 'put' : 'post',
        data: http.adornData({
          categoryId: dataForm.categoryId || undefined,
          status: dataForm.status,
          seq: dataForm.seq,
          grade: dataForm.grade,
          parentId: dataForm.parentId,
          pic: dataForm.pic,
          categoryLangList: categoryLangList.value
        })
      }).then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            visible.value = false
            emit('refreshDataList')
          }
        })
      })
    }
  })
}
// 处理排序输入框
const handleSortValue = () => {
  if (dataForm.seq > 999999999) {
    dataForm.seq = 999999999
    return
  }
  if (dataForm.seq <= 0 || !dataForm.seq) {
    dataForm.seq = 0
  }
}

defineExpose({
  init
})

</script>
